package com.ruitaowang.admin.view.api;

import com.mysql.jdbc.TimeUtil;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.service.queue.RedisMessagePublisher;
import com.ruitaowang.core.utils.TimeUtils;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.CompanyService;
import com.ruitaowang.goods.service.LsMsgService;
import com.ruitaowang.goods.service.RelationsService;
import com.ruitaowang.goods.service.StatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIStatController extends BaseController {

    @Autowired
    private CompanyService companyService;
    @Autowired
    private StatService statService;
//    @Autowired
//    private RedisMessagePublisher redisMessagePublisher;
    @Autowired
    private RelationsService relationsService;
    @Autowired
    private LsMsgService lsMsgService;
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/api/stat/company/income")
    public String statCompany(int days, StatCompany statCompany) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByUserId(user.getId());
        if (ObjectUtils.isEmpty(company)) {
            return this.renderJson(MsgOut.error("no data."));
        }

        statCompany.setCompanyId(company.getCompanyId());
        statCompany.setPage(1);
        statCompany.setRows(days);
        MsgOut o = MsgOut.success(statService.selectForPage(statCompany));
        return this.renderJson(o);
    }

    @RequestMapping("/api/stat/company/user")
    public String statCompanyUser(int days, StatCompanyUser statCompanyUser) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = companyService.selectByUserId(user.getId());
        if (ObjectUtils.isEmpty(company)) {
            return this.renderJson(MsgOut.error("no data."));
        }

        statCompanyUser.setCompanyId(company.getCompanyId());
        statCompanyUser.setPage(1);
        statCompanyUser.setRows(days);
        MsgOut o = MsgOut.success(statService.selectStatCompanyUserForPage(statCompanyUser));
        return this.renderJson(o);
    }

    @RequestMapping("/api/stat/company/update")
    public String statCompanyUser() {
        statService.updateStatCompany();
        statService.updateStatCompanyUser();
        return this.renderJson(MsgOut.success());
    }

    @RequestMapping("/api/caches/test1")
    @Cacheable("test")
    public String cacheTest1(Long userId, String name) {
        LOGGER.debug("performing expensive calculation...");
        return this.renderJson(MsgOut.success());
    }
//    @RequestMapping("/api/messages/pubSubMessage")
//    public String pubSubMessage() {
//        redisMessagePublisher.publish(UUID.randomUUID().toString());
//        return this.renderJson(MsgOut.success());
//    }
    /**
     * @api {get} /api/wap/phb 排行榜-数据接口
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/phb
     *
     * @apiName selectPHB
     * @apiGroup statPHB
     *
     * @apiParam {int} type 排行榜周期参数 1 当日 2 当周 3 当前时间前30天.
     *
     * @apiSuccess {Long} appreciate 点赞数量.
     * @apiSuccess {Long} count 推荐人数.
     * @apiSuccess {string} ranking 本人名次.
     * @apiSuccess {Long} id userId.
     * @apiSuccess {Long} uesrId userId.
     * @apiSuccess {string} headImgUrl 头像.
     * @apiSuccess {string} nickName 名称.
     * @apiSuccess {int} type 排行榜周期参数 1 当日 2 当周 3 当前时间前30天.
     * @apiSuccess {byte} appreciateStatus 判断是否点赞 1 以点赞  2 未点赞
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
                    {
                            "appreciate":0,
                            "count":0,
                            "headImgUrl":"http://wx.qlogo.cn/mmopen/Aqtvh6YDJ6TZnQs24nyymaKibaYMqLlj6X4zvQQwL0icn2GOUAPxPrx6iaePr30syO9zQsibKLCb8WIuLS0H879caA/0",
                            "nickName":"做个有力量的好人",
                            "ranking":"未上榜"
                            "uesrId":1
                    },[{
                                "appreciate":0,
                                "appreciateStatus":2,
                                "count":1844,
                                "headImgUrl":"http://wx.qlogo.cn/mmopen/Aqtvh6YDJ6SP5dMJAIiahP3icvyV3WUeuK6dedtZFJaYwp3HmlTnicuSEprN4pqfV0mGlBqKTxQqslyTMYNEGBoVCGwHibEdwRGe/0",
                                "id":11701,
                                "nickName":"中国旗袍协会美丽天使林美丽会长"
                        },
                        {
                                "appreciate":0,
                                "appreciateStatus":2,
                                "count":1367,
                                "headImgUrl":"http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eo7jXNJ7GvQEzo9LfClh1P0YFUkooVkRRcd1WEQksXNwicszIM8IMspuibMdHSKMdNpOlrVJycOHA9g/132",
                                "id":89940,
                                "nickName":"鱼儿~"
                        }]
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/phb"
     *  }
     */
    @RequestMapping("/api/wap/phb")
    public String selectPHB(RelationsVO relationsVO) {
        SysUser user = LYSecurityUtil.currentSysUser();
//        SysUser user = sysUserService.selectByPK(13L);
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List<Object> outList = new ArrayList<Object>();
        Long stime=0L;
        Long etime=0L;
        //获取时间
        if (relationsVO.getType() == 1){
            //当前数据
           stime = TimeUtils.getLongDayBegin();
           etime = TimeUtils.getLongDayEnd();
        }else if (relationsVO.getType() == 2){
            //本周数据
            stime = TimeUtils.getBeginDayOfWeek();
            etime = TimeUtils.getEndDayOfWeek();
        }else  if (relationsVO.getType() == 3){
            //30天数据
            stime = TimeUtils.getBeginDayOf30();
            etime = System.currentTimeMillis();
        }
        //获取自己的推荐人数 并添加
        RelationsVO rvo = new RelationsVO();
        rvo.setId(user.getId());
        rvo.setEtime(etime);
        rvo.setStime(stime);
        Long count = (long)0;
        if(relationsVO.getLevelType() == 1){
            count=relationsService.selectDZ(rvo);
        } else if(relationsVO.getLevelType() == 2) {
            count=relationsService.selectTowMe(rvo);
        }
        SysUser sysUser=sysUserService.selectByPK(user.getId());
        RelationsVO relationsVO1 = new RelationsVO();
        relationsVO1.setUesrId(user.getId());
        relationsVO1.setNickName(sysUser.getNickname());
        relationsVO1.setHeadImgUrl(sysUser.getHeadimgurl());
        relationsVO1.setCount(count);
        LsMsg ls = new LsMsg();
        ls.setToUserId(user.getId());
        ls.setMsgType((byte)4);
        Long where1=lsMsgService.selectCount(ls);
        relationsVO1.setAppreciate(where1);

        relationsVO.setStime(stime);
        relationsVO.setEtime(etime);
        List<RelationsVO> relationsVOS = new ArrayList<>();
        if(relationsVO.getLevelType() == 1){
            relationsVOS=relationsService.selectPHB(relationsVO);
        } else if(relationsVO.getLevelType() == 2) {
            relationsVOS=relationsService.selectTwoPHB(relationsVO);
        }
        if (ObjectUtils.isEmpty(relationsVOS)){
            relationsVO1.setRanking("未上榜");
        }
        for(int i =0 ;i < relationsVOS.size();i++){
        	RelationsVO tempVO = relationsVOS.get(i);
             LsMsg lsMsg = new LsMsg();
             lsMsg.setToUserId(tempVO.getId());
             lsMsg.setMsgType((byte)4);
             Long appreciate=lsMsgService.selectCount(lsMsg);
             lsMsg.setFromUserId(user.getId());
             List <LsMsg> lsMsgs=lsMsgService.select(lsMsg);
            if (!ObjectUtils.isEmpty(lsMsgs)){
                if (lsMsgs.get(0).getCtime() > TimeUtils.getLongDayBegin()){
                	tempVO.setAppreciateStatus((byte)1);
                }else {
                	tempVO.setAppreciateStatus((byte)2);
                }
            }
             if (user.getId() == tempVO.getId().longValue()){
                 relationsVO1.setRanking(i+1+"");
             }
             tempVO.setAppreciate(appreciate);
         }
        if (ObjectUtils.isEmpty(relationsVO1.getRanking())){
            relationsVO1.setRanking("未上榜");
        }
         //添加排行榜信息
        outList.add(relationsVO1);
        outList.add(relationsVOS);
        return this.renderJson(MsgOut.success(outList));
    }

    /**
     * @api {get} /api/wap/dz 排行榜-点赞接口
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/dz
     *
     * @apiName createDZ
     * @apiGroup statPHB
     *
     * @apiParam {int} toUserId 被点赞的人userID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *           "appreciate":0,
     *           "count":10585,
     *           "headImgUrl":"http://wx.qlogo.cn/mmopen/Aqtvh6YDJ6SP5dMJAIiahPicDAxZxT4rZz2LH7Gb5h4y6cFc5fNAFRoLqpO0vg4uanS7Qta8WK1er9iamGtvKFvOfHNVpP2sSOK/0",
     *           "id":13,
     *           "nickName":"首象共享微传媒"
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/dz"
     *  }
     */
    @RequestMapping("/api/wap/dz")
    public String createDZ(Long toUserId){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        LsMsg lsMsg = new LsMsg();
        lsMsg.setToUserId(toUserId);
        lsMsg.setFromUserId(user.getId());
        lsMsg.setMsgType((byte)4);
        List<LsMsg> lsMsgs=lsMsgService.select(lsMsg);
        if (!ObjectUtils.isEmpty(lsMsgs)){
            if (lsMsgs.get(0).getCtime() > TimeUtils.getLongDayBegin()){
                MsgOut o = MsgOut.success("请勿重复点赞");
                o.setCode(5);
                return this.renderJson(o);
            }
        }
        return this.renderJson(MsgOut.success(lsMsgService.insert(lsMsg)));
    }
}
